package com.apes.supplier.platform;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.pi.model.Timestamp;
import com.apes.pi.repository.TimestampRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.masterdata.product.repository.BrandRepository;
import com.apes.scm.masterdata.product.repository.CategoryRepository;
import com.apes.supplier.model.SupplierCommodity;
import com.apes.supplier.repository.SupplierCommodityRepository;
import com.apestech.framework.json.JSON;
import com.apestech.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service("supplierPlatformService")
public class SupplierPlatformService extends DomainService {

    @Autowired
    TimestampRepository timestampRepository;

    @Autowired
    SupplierCommodityRepository supplierCommodityRepository;

    public void beImportTodo (SimpleRequest request) {
        JSONObject jo = request.getJO();
        jo.put("userId", request.getSession().getUserId());
        jo.put("userName", request.getSession().getUserName());
        Object invoke = invoke("auto.supplierPlatformTodo.beImportTodo", jo);
        String message = JSONObject.parseObject(invoke.toString()).getJSONObject("header").getString("message");
        if (message.indexOf("成功") < 0) {
            throw new RuntimeException(message);
        }
        
    }

    public void confirmAll (SimpleRequest request) {
        JSONObject jo = request.getJO();
        jo.put("userId", request.getSession().getUserId());
        jo.put("userName", request.getSession().getUserName());
        Object invoke = invoke("auto.supplierPlatformTodo.confirmAll", jo);
    }

    /**
     * 推送消息队列
     * @param request
     * @return
     */
    public JSONObject MQDCSupplierCommodity (SimpleRequest request) {
        MQUtil.publish("supplierPlatformTodo.handleDCSupplierCommodity", "", request.getJO());
        return request.getJO();
    }


    public void handleDCSupplierCommodity(SimpleRequest request) {
        checkData(request.getJO().getJSONArray("data"));
    }

    private void checkData(JSONArray param) {
        List<SupplierCommodity> supplierCommodities = new ArrayList<>();
        for (Object o : param) {
            JSONObject jsonObject = (JSONObject)o;
            supplierCommodities.add(toSupplierCommodity(jsonObject));
        }
        List<SupplierCommodity> deleteSupplierCommodities = new ArrayList<>();
        List<SupplierCommodity> addSupplierCommodities = new ArrayList<>();
        List<SupplierCommodity> updateSupplierCommodities = new ArrayList<>();


        for (SupplierCommodity supplierCommodity : supplierCommodities) {
            //  品牌字段为空，赋值个 “无”
            if (StringUtil.isEmpty(supplierCommodity.getBrandName()))
                supplierCommodity.setBrandName("无");
            if (("上架".equals(supplierCommodity.getState()) || supplierCommodity.getState() == null || "".equals(supplierCommodity.getState()) )&&
                    supplierCommodity.getContrastBrand() != null &&
                    supplierCommodity.getContrastBrand().getCharacter() != null &&
                    supplierCommodity.getContrastBrand().getSubQuality() != null) {
                supplierCommodity.setState("up");
                List<SupplierCommodity> supplierCommodityBySource = supplierCommodityRepository.findSupplierCommodityBySource(supplierCommodity.getSource());
                if (supplierCommodityBySource == null || supplierCommodityBySource.size() == 0) {
                    addSupplierCommodities.add(supplierCommodity);
                } else {
                    List<SupplierCommodity> collect = supplierCommodityBySource.stream().filter(supplierCommodity1 -> supplierCommodity1.getContrastBrand().getId() == supplierCommodity.getContrastBrand().getId()).collect(Collectors.toList());
                    supplierCommodity.setId(supplierCommodityBySource.size() > 1 ? collect.get(0).getId() : supplierCommodityBySource.get(0).getId());
                    supplierCommodity.setVersion(supplierCommodityBySource.size() > 1 ? collect.get(0).getVersion() : supplierCommodityBySource.get(0).getVersion());
                    updateSupplierCommodities.add(supplierCommodity);
                }
            } else if ("下架".equals(supplierCommodity.getState())) {
                List<SupplierCommodity> supplierCommodityBySource = supplierCommodityRepository.findSupplierCommodityBySource(supplierCommodity.getSource());
                if (supplierCommodityBySource != null && supplierCommodityBySource.size() > 0) {
                    deleteSupplierCommodities.add(supplierCommodity);
                }
            }
        }
        supplierCommodityRepository.deleteAll(deleteSupplierCommodities);
        supplierCommodityRepository.saveAll(updateSupplierCommodities);
        supplierCommodityRepository.saveAll(addSupplierCommodities);
    }

    private SupplierCommodity toSupplierCommodity (JSONObject param) {
        SupplierCommodity supplierCommodity = new SupplierCommodity();
        supplierCommodity.setBusinessId(param.getString("BUSINESS_ID"));
        supplierCommodity.setBrandName(param.getString("BRAND_NAME"));
        supplierCommodity.setBrandModel(param.getString("BRAND_MODEL"));
        supplierCommodity.setPartName(param.getString("PART_NAME"));
        supplierCommodity.setUomName(param.getString("UOM_NAME"));
        supplierCommodity.setUniversalPartNumber(param.getString("UNIVERSAL_PART_NUMBER"));
        supplierCommodity.setContrastPartId(param.getString("CONTRAST_PART_ID"));
        supplierCommodity.setProductDescription(param.getString("PRODUCT_DESCRIPTION"));
        supplierCommodity.setInventoryQuantity(param.getDoubleValue("INVENTORY_QUANTITY"));
        supplierCommodity.setNotaxPrice(param.getDoubleValue("UNTAX_PRICE"));
        supplierCommodity.setState(param.getString("ONSHELVES"));
        PartyRole supplier = SpringManager.getBean(PartyRoleRepository.class).findOne(param.getString("SUPPLIER_ID").substring(2));
        supplierCommodity.setSupplier(supplier);
        supplierCommodity.setSizes(param.getString("SIZES"));
        supplierCommodity.setOrigin(param.getString("ORIGIN"));
        supplierCommodity.setCreator(param.getString("LRR"));
        supplierCommodity.setCreateDate(param.getDate("LRRQ_SJ"));
        supplierCommodity.setSource(param.getString("ID"));
        supplierCommodity.setQualityName(param.getString("QUALITY_NAME"));
        supplierCommodity.setPackingContent(param.getString("BZHL"));
        supplierCommodity.setReplacementPartNumber(param.getString("BUSINESS_ID"));
        supplierCommodity.setContrastOrigin(param.getString("CONTRAST_ORIGIN"));
        if (param.getString("CONTRAST_BRAND_ID") != null) {
            Brand brand = SpringManager.getBean(BrandRepository.class).findOne(param.getString("CONTRAST_BRAND_ID"));
            supplierCommodity.setContrastBrand(brand);
        }
        if (param.getString("CATEGORY_ID") != null) {
            Category category = SpringManager.getBean(CategoryRepository.class).findOne(param.getString("CATEGORY_ID"));
            supplierCommodity.setCategory(category);
        }
        return supplierCommodity;
    }

    public Object reportData(SimpleRequest request) {
        com.apestech.framework.json.JSONObject json = new com.apestech.framework.json.JSONObject();
        try {
            JSONObject jo = request.getJO();
            for (Object condition : jo.getJSONArray("condition")) {
                if ("STATES".equals(JSON.toJSON(condition).getString("field")) && "normal".equals(JSON.toJSON(condition).getString("value"))) {
                    jo.put("queryid", jo.getString("queryid").replace("Debug",""));
                }
            }
            json = JSON.toJSON(jo.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return invoke("supplierPlatformTodo.reportData", json);
    }

    public String toDataCenterString(SimpleRequest request) {
        return request.getJO().toString();
    }
}
